from django.template.loader import render_to_string
from django.conf import settings
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site
import re
import sha
import random

SHA1_RE = re.compile('^[a-z0-9A-Z]{30}$')

class ProfileManager(models.Manager):

    def create(self, username, password, email):
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()
        profile = Profile(user = new_user)
        profile.user_id = new_user.id
        salt = sha.new(str(random.random())).hexdigest()[:5]
        activation = sha.new(salt+new_user.username).hexdigest()
        profile.activation_key = activation
        profile.save()
        current_site = Site.objects.get_current()
        
        subject = render_to_string('profile/activation_email_subject.txt',)
        subject = ''.join(subject.splitlines())
        
        message = render_to_string('profile/activation_email.txt',
                                   { 'key': profile.activation_key,
                                     'site_name': settings.DEFAULT_SITE_NAME,
                                     'u_username': new_user.username,
                                     'domain' : settings.DEFAULT_SITE_DOMAIN,})
        
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])

    def activate(self, activation_key):
        try:
            profile = self.get(activation_key=activation_key)
        except self.model.DoesNotExist:
            return False
        user = profile.user
        user.is_active = True
        user.save()
        profile.activation_key = "Activated"
        profile.save()
        return profile

class Profile(models.Model):
    user = models.ForeignKey(User, unique = True)
    firstname = models.CharField(max_length = 20)
    lastname = models.CharField(max_length = 20)
    birthdate = models.DateField(auto_now_add=True)
    university = models.CharField(max_length = 30)
    faculty = models.CharField(max_length = 30)
    about = models.TextField()
    activation_key = models.CharField(_('activation key'), max_length=40)
    activated = models.BooleanField(default = False)

    objects = ProfileManager()
    
    class Meta:
        verbose_name = _('profile')
        verbose_name_plural = _('profiles')

    def __unicode__(self):
        return self.lastname
